package com.momo.encoderHandler3;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

/**
 * @author Kagome
 * @title: MyClientHandler
 * @projectName boot2.X-netty
 * @description: TODO
 * @date 2019/6/2 16:22
 */
public class MyClientHandler extends SimpleChannelInboundHandler<PersionProtocol> {
    private int count = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, PersionProtocol msg) throws Exception {
        byte[] content = msg.getContent();
        int length = msg.getLength();
        System.out.println("客户端接收到的数据:");
        System.out.println("长度:"+length);
        System.out.println("内容:"+new String(content, Charset.forName("utf-8")));
        System.out.println("执行次数"+(++count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 10; i++) {
            String sendMsg = "send from client地方 ";
            byte[] content = sendMsg.getBytes(Charset.forName("utf-8"));
            int length = sendMsg.getBytes(Charset.forName("utf-8")).length;
            PersionProtocol persionProtocol = new PersionProtocol();
            persionProtocol.setLength(length);
            persionProtocol.setContent(content);
            ctx.writeAndFlush(persionProtocol);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
